<template>
    <view class="page">
        <!-- <NavBar title="个人中心"></NavBar> -->

        <view class="header">
            <view class="user">
                <navigator class="avatar" url="/pages/setting/setting" hover-class="none" open-type="navigate">
                    <uv-avatar :src="user.avatar" size="120rpx"></uv-avatar>
                </navigator>
                <view class="info" v-if="user.vipKind">
                    <view class="user-name">
                        <view class="user-name-text">{{ user.nickname }}</view>
                        <view class="vip">
                            <image src="@/static/images/icon_VIP.png" class="vip-icon" />
                        </view>
                    </view>
                    <view class="vip-time">vip到期：{{ user.vipEnd }}</view>
                </view>
                <navigator v-else class="user-name" url="/pages/setting/setting" hover-class="none"
                    open-type="navigate">
                    {{ user.nickname }}
                </navigator>


                <navigator v-if="!token" class="user-btn" url="/pages/login/login" hover-class="none"
                    open-type="navigate">登录
                </navigator>
                <navigator v-if="!token" class="user-btn" url="/pages/register/register" hover-class="none"
                    open-type="navigate">注册
                </navigator>

            </view>
        </view>

        <view class="wallet">
            <view class="item">
                <view class="icon">
                    <image class="yundian" src="@/static/images/icon_yundian.png"></image>
                </view>
                <view class="quantity">云点:{{ user.balance || 0 }}</view>
            </view>
            <view class="item">
                <view class="icon">
                    <image class="jifen" src="@/static/images/icon_jifen.png"></image>
                </view>
                <view class="quantity">积分:{{ user.integral || 0 }}</view>
            </view>

            <image src="../../static/images/icon_shuaxin@2x.png"
                style="width: 40rpx;height: 40rpx;position: absolute;right: 32rpx;" @click="refresh"></image>
        </view>

        <view class="recharge-type">
            <view class="recharge-type-item" v-for="(item, index) in rechargeType" :key="index"
                :class="{ actived: index == rechargeTypeIndex }" @click="changeChargeType(index)">{{ item }}</view>
        </view>

        <view class="goods" v-if="rechargeTypeIndex == 1">
            <view class="item" :class="{ actived: index == i }" v-for="(item, i) in goods" :key="item.id"
                @click="selectItem(i)">
                <view class="info">
                    <view class="name">
                        {{ item.name }}
                        <view class="small" v-if="item.integral">(加赠{{ item.integral }}积分)</view>
                    </view>
                    <view class="tip">{{ item.info }}</view>
                </view>
                <view class="suggest" v-if="item.subscript">{{ item.subscript }}</view>
                <view class="pirce">
                    <view class="small">￥</view>
                    <view class="money">{{ item.cost }}</view>
                </view>
            </view>
        </view>

        <view class="goods vip" v-else>
            <view class="item" :class="{ actived: index == i }" v-for="(item, i) in goods" :key="item.id"
                @click="selectItem(i)">
                <view class="info">
                    <view class="name">
                        {{ item.name }}
                        <view class="small" v-if="item.integral">(加赠{{ item.integral }}积分)</view>
                    </view>
                    <view class="desc">
                        <view class="desc-item" v-for="(items, index) in item.info_a.split(' ')" :key="index">{{ items
                            }}</view>
                    </view>
                    <view class="tip" v-for="(items, index) in item.info.split(' ')" :key="index"
                        v-show="items.length > 0">{{ items }}</view>
                </view>

                <view class="suggest" v-if="item.subscript">{{ item.subscript }}</view>
                <view class="pirce">
                    <view class="small">￥</view>
                    <view class="money">{{ item.cost }}</view>
                </view>
            </view>
        </view>




        <view class="controller">
            <view class="work-btn-style btn" @click="recharge">充值</view>
        </view>

        <!-- loading -->
        <uv-loading-page :loading="loading" :loadingText="loadingText" font-size="24rpx"
            bgColor="rgba(0,0,0,0.5)"></uv-loading-page>
    </view>
</template>

<script setup>
import {
    ref
} from 'vue';
import {
    onShow,
    onLoad
} from '@dcloudio/uni-app'

//pinia
import {
    storeToRefs
} from 'pinia'
import {
    useUserStore
} from "@/stores/useUserStore.js"
import {
    useLoadingStore
} from "@/stores/useLoadingStore.js"

// 获取pinia的数据
const userStore = useUserStore()
const loadingStore = useLoadingStore()

// 从pinia的数据中结构出值并做响应式
const {
    user,
    token
} = storeToRefs(userStore)
const {
    loading
} = storeToRefs(loadingStore)

//api

import {
    apiGetGoods,
    apiGetwechatBrowserPay,
    apiGetOutSideBrowserPay,
    apiGetPaymentStatus
} from '@/api/accountApi.js'
import {
    apiGetUserInfo,
    apiGetWchatCode
} from '@/api/authApi.js'


// 充值套餐
const rechargeType = ref(['开通VIP无限用', '云点充值'])
const rechargeTypeIndex = ref(0)
const goodsAll = ref([])               //所有充值套餐列表
const goods = ref([])               //当前类型的充值套餐列表
const index = ref(0)

const loadingText = ref('正在发起支付中..')

//定时器
const count = ref(100000)

const orderTimer = ref({})


// 获取充值套餐
const getGoods = async () => {
    let res = await apiGetGoods()
    goodsAll.value = res.data
    changeChargeType(0)
}

// 获取用户信息
const getUserInfo = async () => {
    let res = await apiGetUserInfo()
    userStore.setUser(res.data)
}

//刷新
const refresh = () => {
    getUserInfo()
    getGoods()
}

// 修改充值类型
const changeChargeType = (i) => {
    goods.value = []
    index.value = 0
    rechargeTypeIndex.value = i
    goodsAll.value.forEach(e => {
        if (rechargeTypeIndex.value == 0) {
            if (e.kind == 2) {
                goods.value.push(e)
            }
        }
        if (rechargeTypeIndex.value == 1) {
            if (e.kind == 1) {
                goods.value.push(e)
            }
        }
    });
}
//选择套餐
const selectItem = (i) => {
    index.value = i
}

// 充值确认
const recharge = async () => {
    // #ifdef H5
    let ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        getWchatCode()
    } else {
        outSidePay()
        // uni.showToast({
        // 	title: "充值系统升级中，请到官网进行充值",
        // 	icon: "none",
        // })
    }
    // #endif
}

const outSidePay = async () => {
    let res = await apiGetOutSideBrowserPay({
        goodsId: goods.value[index.value].id,
    })
    orderTimer.value = setInterval(() => {
        getPaymentStatus(res.data.id)
        count.value = count.value - 1

    }, 3000)
    window.location.href = res.data.code_url;

}

// 获取支付状态
const getPaymentStatus = async (oid) => {
    let res = await apiGetPaymentStatus({
        id: oid
    })
    if (res.data?.status == 16) {
        loadingStore.setLoading(false)
        // uni.showToast({
        // 	icon: 'success',
        // 	title: '支付成功'
        // })
        // //成功后跳转到订单页
        setTimeout(function () {
            uni.reLaunch({
                url: '/pages/user/user'
            });
        }, 2000)
    }

    if (res.data?.status == 16 || count.value == 0) {
        clearInterval(orderTimer.value)
    }

}


//微信浏览器内支付前获取code的请求
const getWchatCode = async () => {
    let res = await apiGetWchatCode({
        goodsId: goods.value[index.value].id,
    })
    window.location.href = res.data;

    // let url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx711603713cc801b7&redirect_uri=https://wap.ytaiccg.com/recharge/routing&response_type=code&scope=snsapi_base&state=1730746355388067841#wechat_redirect'

    // console.log(url);
    // let appid = 'wx9c907e79891f91fe';
    // let uri = encodeURIComponent(link);
    // let authURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;


    // // 假设我们有一个URL查询字符串
    // const queryString = res.data.split('?')[1]

    // // 创建URLSearchParams实例
    // const params = new URLSearchParams(queryString);


    // // 获取单个参数的值
    // let appid = params.get('appid'); // 返回 'appid'
    // // let redirect_uri = params.get('redirect_uri'); // 返回 'redirect_uri'
    // let redirect_uri = encodeURIComponent('https://demo.jizhi007.com/pages/recharge/recharge'); // 返回 'redirect_uri'
    // let response_type = params.get('response_type'); // 返回 'response_type'
    // let scope = params.get('scope'); // 返回 'response_type'
    // let state = params.get('state'); // 返回 'state'

    // let url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid' + appid + '&redirect_uri=' + redirect_uri + '&response_type=' + response_type + '&scope=' + scope + '&state=' + state + '#wechat_redirect'

    // console.log(url);

    // location.href = url

}

//微信内部浏览器支付
const getwechatBrowserPay = (data = {}) => {
    // console.log(window.jWeixin);
    let code = data?.code ?? ''
    let goodsId = data?.state ?? ''

    if (code && goodsId) {
        loadingStore.setLoading(true)
        apiGetwechatBrowserPay({
            code: code,
            goodsId: goodsId
        }).then(res => {
            if (res.code === 0) {

                WeixinJSBridge.invoke(
                    'getBrandWCPayRequest', {
                    "appId": res.data.appId, //公众号名称，由商户传入
                    "timeStamp": res.data.timeStamp, //时间戳     
                    "nonceStr": res.data.nonceStr, //随机串     
                    "package": res.data.packageVal,
                    "signType": res.data.signType, //微信签名方式：     
                    "paySign": res.data.paySign //微信签名 
                },
                    function (ress) {
                        if (ress.err_msg == "get_brand_wcpay_request:ok") {
                            loadingStore.setLoading(false)
                            uni.showToast({
                                icon: 'success',
                                title: '支付成功'
                            })
                            // //成功后跳转到订单页
                            setTimeout(function () {
                                uni.reLaunch({
                                    url: '/pages/afterService/afterService'
                                });
                            }, 2000)
                        } else if (ress.err_msg == "get_brand_wcpay_request:cancel") {
                            loadingStore.setLoading(false)
                            uni.showToast({
                                icon: "none",
                                title: "'已取消支付"
                            })
                        } else {
                            loadingStore.setLoading(false)
                            uni.showToast({
                                icon: "none",
                                title: "支付失败"
                            })
                        }
                    }
                );
            }
        }).catch(err => {
            loadingStore.setLoading(false)
        })

    }
}

onLoad((option) => {

    goods.value = []
    // 登录状态下获取我的模型
    if (token.value) {
        getGoods()
    }

    // #ifdef H5
    getwechatBrowserPay(option)
    // #endif


    // #ifdef H5
    // let code = option?.code ?? ''
    // let goodsId = option?.state ?? ''
    // if (code && goodsId) {
    //     getwechatBrowserPay({
    //         code: code,
    //         goodsId: goodsId
    //     })
    // }

    // // 为了本地开发方便，这里设置一个参数，用来检测是否再次跳转成功
    // let isredirect = option?.isredirect ?? false

    // console.log(code, '--code');
    // console.log(goodsId, '--goodsId ');
    // console.log(isredirect, '--isredirect');
    // if (code && goodsId) {
    //     if (!isredirect) {
    //         let url = 'http://cloudmap.com/pages/recharge/recharge?code=' + code + '&state=' + goodsId + '&isredirect=true'
    //         location.href = url
    //     } else {
    //         getwechatBrowserPay({
    //             code: code,
    //             goodsId: goodsId
    //         })
    //     }
    // }

    // #endif
})
</script>

<style lang="scss" scoped>
.page {
    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 56rpx;

        .user {
            display: flex;
            align-items: center;

            .avatar {
                width: 120rpx;
                height: 120rpx;
                background: #ececec;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-right: 20rpx;
            }

            .user-btn,
            .user-name {
                display: flex;
                flex-direction: row;
                color: #fff;
                margin-right: 6rpx;
            }

            .info {
                .user-name {
                    height: 28rpx;

                    .user-name-text {
                        height: 100%;
                        display: flex;
                        align-items: center;
                        margin-right: 12rpx;
                        font-size: 32rpx;
                    }

                    .vip {
                        width: 15rpx;
                        height: 14rpx;

                        .vip-icon {
                            width: 100%;
                            height: 100%;
                            display: block;
                        }
                    }
                }

                .vip-time {
                    font-size: 20rpx;
                    color: #e6e6e6;
                    margin-top: 14rpx;
                }

            }

        }

        .setting,
        .setting-img {
            width: 50rpx;
            height: 50rpx;
        }

    }

    .wallet {
        width: 100%;
        height: 64rpx;
        display: flex;
        flex-direction: row;
        align-items: center;

        .item {
            display: flex;
            align-items: center;
            margin-right: 20rpx;

            .icon {
                width: 64rpx;
                height: 64rpx;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                border: 2rpx solid #999999;
                box-sizing: border-box;
                background: #000;
                z-index: 1;

                .yundian {
                    width: 36rpx;
                    height: 28rpx;
                }

                .jifen {
                    height: 36rpx;
                    width: 28rpx;
                }
            }

            .quantity {
                height: 56rpx;
                display: flex;
                align-items: center;
                border: 2rpx solid #999999;
                box-sizing: border-box;
                color: #fff;
                display: flex;
                margin-left: -20rpx;
                padding-left: 30rpx;
                width: 220rpx;
                border-radius: 0 15rpx 15rpx 0;
                font-size: 28rpx;
                font-weight: 700;
            }
        }

        .record,
        .navigator-wrap {
            flex: 1;
            height: 56rpx;
            background: #333333;
            border-radius: 15rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20rpx;
            font-weight: 500;
            color: #999;
        }
    }

    .recharge-type {
        width: 686rpx;
        height: 64rpx;
        border: 2rpx solid #e6e6e6;
        border-radius: 33rpx;
        margin: 60rpx auto 0;
        display: flex;

        .recharge-type-item {
            width: 343rpx;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 30rpx;
            color: #fff;
            border-radius: 32rpx;

            &.actived {
                background: #ffcb30;
                border: 2rpx solid #ffcb30;
                color: #000;
                box-sizing: content-box;
                margin-top: -2rpx;
            }
        }
    }

    .btn {
        width: 100%;
        height: 72rpx;
        font-size: 24rpx;
        font-weight: 700;
        color: #000;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 24rpx auto 80rpx;
    }

    .goods {
        width: 100%;
        display: flex;
        flex-direction: column;
        margin-top: 36rpx;
        margin-bottom: 78rpx;

        .item {
            width: 100%;
            height: 160rpx;
            background: #1a1a1a;
            border-radius: 15rpx;
            margin-bottom: 16rpx;
            display: flex;
            flex-direction: row;
            padding: 0 32rpx;
            box-sizing: border-box;
            justify-content: space-between;
            align-items: center;
            position: relative;
            overflow: hidden;

            &.actived {
                background: #333333;
                border: 4rpx solid #ffcb30;
            }

            .suggest {
                width: 80rpx;
                height: 40rpx;
                background: #ffde7d;
                border-radius: 0rpx 0rpx 0rpx 15rpx;
                font-size: 22rpx;
                font-weight: 500;
                color: #000;
                position: absolute;
                top: 0;
                right: 0;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .info {
                display: flex;
                flex-direction: column;
                justify-content: center;

                .name {
                    font-size: 30rpx;
                    height: 30rpx;
                    font-weight: 500;
                    color: #fff;
                    display: flex;
                    margin-bottom: 20rpx;

                    .small {
                        font-size: 20rpx;
                        margin-top: 10rpx;
                        margin-left: 20rpx;
                    }
                }

                .tip {
                    font-size: 20rpx;
                    color: #fff;
                }
            }

            .pirce {
                display: flex;

                .small {
                    font-size: 30rpx;
                    color: #fff;
                    margin-top: 34rpx;
                }

                .money {
                    color: #fff;
                    font-size: 64rpx;
                }
            }
        }

        &.vip {
            width: 100%;

            .item {
                height: 300rpx;
                width: 100%;
                background: #1a1a1a;
                border-radius: 15rpx;
                margin-bottom: 16rpx;
                display: flex;
                flex-direction: row;
                padding: 0 32rpx;
                box-sizing: border-box;
                justify-content: space-between;
                align-items: center;
                position: relative;
                overflow: hidden;

                &.actived {
                    background: #333333;
                    width: 100%;
                    border: 4rpx solid #ffcb30;
                }

                .info {
                    display: flex;
                    flex-direction: column;
                    justify-content: flex-start;
                    height: 100%;

                    .name {
                        font-size: 30rpx;
                        font-weight: 700;
                        color: #fff;
                        display: flex;
                        margin: 42rpx 0 16rpx;
                        height: auto;

                        .small {
                            font-size: 20rpx;
                            margin-top: 10rpx;
                            margin-left: 20rpx;
                        }
                    }

                    .desc {
                        height: 28rpx;
                        width: 100%;
                        display: flex;
                        margin-bottom: 16rpx;

                        .desc-item {
                            height: 100%;
                            padding: 0 8rpx;
                            background: #ffde7d;
                            border-radius: 5rpx;
                            font-size: 20rpx;
                            color: #000;
                            font-weight: 400;
                            margin-right: 8rpx;
                        }
                    }

                    .tip {
                        font-size: 20rpx;
                        height: 20rpx;
                        color: #fff;
                        margin-bottom: 12rpx;
                    }
                }

                .pirce {
                    flex-wrap: wrap;
                    justify-content: end;

                    .origin-price {
                        font-size: 20rpx;
                        color: #999;
                        text-decoration: line-through;
                        width: 100%;
                        text-align: right;
                    }
                }
            }
        }
    }


    .controller {
        height: 112rpx;
        width: 100%;
        background: #191919;
        position: fixed;
        bottom: var(--window-bottom);
        left: 0;
        padding: 0 32rpx;
        box-sizing: border-box;

        .btn {
            width: 100%;
            height: 78rpx;
            border-radius: 39rpx;
            color: #080808;
            align-items: center;

            .btn-text {
                font-size: 30rpx;
                font-weight: 700;
                line-height: 78rpx;
            }

            .btn-price {
                font-weight: 500;
                font-size: 18rpx;
                line-height: 60rpx;
                letter-spacing: 2.8rpx;
            }
        }
    }

}
</style>